﻿using System;
using System.Diagnostics;
using System.Xml;
using Microsoft.Phone.Info;

namespace Phoenix.Diagnostics
{
    public static class Information
    {
        /// <summary>
        /// Gets an attribute from the Windows Phone App Manifest App element
        /// </summary>
        /// <param name="attributeName">the attribute name</param>
        /// <returns>the attribute value</returns>
        public static string GetAppAttribute(string attributeName)
        {
            const string appManifestName = "WMAppManifest.xml";
            const string appNodeName = "App";

            var settings = new XmlReaderSettings {XmlResolver = new XmlXapResolver()};

            using (var rdr = XmlReader.Create(appManifestName, settings))
            {
                rdr.ReadToDescendant(appNodeName);
                if (!rdr.IsStartElement())
                {
                    throw new FormatException(appManifestName + " is missing " + appNodeName);
                }

                return rdr.GetAttribute(attributeName);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>Memory usage in Mb's when debugger is attached, otherwise 0</returns>
        public static double GetMemoryUsage()
        {
            if (!Debugger.IsAttached) return 0;

            var number = (long) DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
            var memoryUsageInMb = number/(1024.0*1024.0);
            return memoryUsageInMb;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>Peak Memory usage in Mb's when debugger is attached, otherwise 0</returns>
        public static double GetPeakMemoryUsage()
        {
            if (!Debugger.IsAttached) return 0;

            var number = (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
            var memoryUsageInMb = number/(1024.0*1024.0);
            return memoryUsageInMb;
        }
    }
}
